package com.hqd.ch03.v34.web.method.annotation;

import com.hqd.ch03.v34.core.MethodParameter;
import com.hqd.ch03.v34.factory.ConfigurableBeanFactory;
import com.hqd.ch03.v34.web.bind.annotation.RequestHeader;
import com.hqd.ch03.v34.web.context.request.NativeWebRequest;
import com.hqd.ch03.v34.web.servlet.mvc.method.annotation.AbstractNamedValueMethodArgumentResolver;

import java.util.Map;

public class RequestHeaderMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {

    public RequestHeaderMethodArgumentResolver(ConfigurableBeanFactory beanFactory) {
        super(beanFactory);
    }


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return (parameter.hasParameterAnnotation(RequestHeader.class) &&
                !Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType()));
    }

    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        RequestHeader ann = parameter.getParameterAnnotation(RequestHeader.class);
        return new RequestHeaderNamedValueInfo(ann);
    }

    @Override
    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
        String[] headerValues = request.getHeaderValues(name);
        if (headerValues != null) {
            return (headerValues.length == 1 ? headerValues[0] : headerValues);
        } else {
            return null;
        }
    }

    @Override
    protected void handleMissingValue(String name, MethodParameter parameter) {
    }

    @Override
    protected void handleMissingValueAfterConversion(
            String name, MethodParameter parameter, NativeWebRequest request) throws Exception {

    }

    private static final class RequestHeaderNamedValueInfo extends NamedValueInfo {

        private RequestHeaderNamedValueInfo(RequestHeader annotation) {
            super(annotation.name(), annotation.required(), annotation.defaultValue());
        }
    }

}

